<template>
  <div class="sms-template-container">
    <!-- 页面标题区域 -->
    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧：模版分组树 -->
      <el-col :xs="24" :sm="6" :md="4" :lg="4">
        <el-card shadow="hover" class="template-group-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-folder"></i>
              <span>模版分组</span>
            </div>
            <div class="header-actions">
              <el-button type="text" class="add-group-btn" @click="handleAddGroup">
                <i class="el-icon-plus"></i> 新建分组
              </el-button>
            </div>
          </div>

          <div v-if="loading" class="tree-loading">
            <i class="el-icon-loading"></i>
            <span>加载中...</span>
          </div>

          <el-tree :data="templateGroups" :props="defaultProps" :expand-on-click-node="false"
                  :filter-node-method="filterNode" ref="tree" node-key="groupId" default-expand-all highlight-current
                  @node-click="handleNodeClick">
            <span class="custom-tree-node show-hide" slot-scope="{node,data}">
              <span class="node-label">
                <i v-if="data.groupId == 0" class="el-icon-s-home tree-icon" />
                <i v-else class="el-icon-document tree-icon" />
                {{ data.groupName }}
              </span>
              <span class="node-actions">
                <i class="el-icon-plus action-icon" title="增加" @click.stop="handleAddGroup(data)" v-if="data.groupId == 0"></i>
                <i class="el-icon-edit action-icon" title="编辑" @click.stop="handleGroupUpdate(data)" v-if="data.groupId != 0"></i>
                <i class="el-icon-delete action-icon" title="删除" @click.stop="handleGroupDelete(node, data)" v-if="data.groupId != 0"></i>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 中间：模版列表 -->
      <el-col :xs="24" :sm="18" :md="14" :lg="14">
        <el-card shadow="hover" class="template-list-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-document"></i>
              <span>模版列表</span>
            </div>
            <div class="header-actions">
              <el-button type="primary" icon="el-icon-plus" @click="handleCreateTemplate">
                新建模版
              </el-button>
            </div>
          </div>
          <!-- 筛选工具栏 -->
          <div class="filter-toolbar">
            <div class="left-section">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable style="width: 220px">
                <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </div>
            <div class="right-section">
              <el-input
                v-model="searchQuery"
                placeholder="搜索模版名称或内容"
                prefix-icon="el-icon-search"
                clearable
                size="small"
                style="width: 220px"
                @clear="handleSearch"
                @keyup.enter.native="handleSearch"
              />
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleSearch"
                style="margin-left: 8px;">
                搜索
              </el-button>
              <el-button
                icon="el-icon-refresh"
                size="small"
                @click="resetSearch"
                style="margin-left: 8px;">
                重置
              </el-button>
            </div>
          </div>

          <!-- 模版表格 -->
          <el-table
            :data="templateList"
            style="width: 100%"
            :header-cell-style="tableHeaderStyle"
            ref="templateForm"
            border
            @row-click="handleRowClick"
            class="custom-table"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="模版ID" align="center" prop="templateId" width="140" />
            <el-table-column label="模版名称" prop="templateName" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column label="签名名称" align="center" prop="signatureName" min-width="80" :show-overflow-tooltip="true" />
            <el-table-column label="模版内容" prop="templateContent" min-width="250" show-overflow-tooltip></el-table-column>
            <el-table-column label="模版类型" prop="templateType" width="90" align="center">
                      <template slot-scope="scope">
          {{ scope.row.templateType == 1 ? '普通短信' : scope.row.templateType == 2 ? '智能短信' : scope.row.templateType }}
        </template>
            </el-table-column>
            <el-table-column label="审核状态" wprop="auditStatus" idth="90" align="center">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus"/>
              </template>
            </el-table-column>
            <el-table-column label="审核意见" align="center" prop="auditRemarks" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="申请说明" align="left" prop="applyDescription" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="操作" width="220" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click.stop="scope.row.auditStatus === 'successful' ? $message.warning('审核成功的模版不能修改') : handleUpdate(scope.row)"
                  class="action-button"
                  :disabled="scope.row.auditStatus === 'successful'"
                >编辑</el-button>
                <el-button type="text" size="small" @click.stop="handlePreviewTemplate(scope.row)" class="action-button">预览</el-button>
                <el-button type="text" size="small" @click.stop="handleCopyTemplate(scope.row)" class="action-button">复制</el-button>
                <el-button type="text" size="small" @click.stop="handleDelete(scope.row)" class="action-button">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            class="custom-pagination"
          />
        </el-card>
      </el-col>

      <!-- 右侧：模版详情和变量管理 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6">
        <!-- 模版详情 -->
        <el-card shadow="hover" class="template-detail-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-document-copy"></i>
              <span>模版详情</span>
            </div>
            <div class="header-actions">
              <el-button v-if="selectedTemplate" type="text" icon="el-icon-edit" @click="sendSmsTest(selectedTemplate)" class="action-button">发送测试</el-button>
            </div>
          </div>

          <div v-if="selectedTemplate" class="template-detail-content">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="模版名称">{{ selectedTemplate.templateName }}</el-descriptions-item>
            <el-descriptions-item label="审核状态">
              <dict-tag :options="dict.type.audit_status" :value="selectedTemplate.auditStatus"/>
            </el-descriptions-item>
            <el-descriptions-item label="模版内容">
              <div class="template-content-preview">{{ selectedTemplate.templateContent }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="审核意见" >
              <div class="reject-reason">{{ selectedTemplate.auditRemarks || '无' }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ selectedTemplate.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ selectedTemplate.updateTime }}</el-descriptions-item>
              <!-- <el-descriptions-item label="使用次数">{{ selectedTemplate.usageCount }}</el-descriptions-item> -->
          </el-descriptions>

          <!-- 模版预览 -->
          <div class="template-preview-section">
            <div class="section-title">消息预览</div>
            <div class="phone-preview">
              <div class="phone-frame">
                <div class="phone-header">
                  <div class="phone-time">{{ currentTime }}</div>
                </div>
                <div class="phone-content">
                  <div class="message-bubble">
                    <div class="message-sender">【云数据库】</div>
                    <div class="message-content">{{ previewContent }}</div>
                    <div class="message-time">{{ currentTime }}</div>
                  </div>
                </div>
              </div>
            </div>
            </div>
          </div>

          <div v-else class="empty-details-container">
            <el-empty description="请从左侧列表中选择一个模板查看详情"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 模版编辑对话框 -->
    <el-dialog
      :title="dialogType === 'create' ? '新建模版' : '编辑模版'"
      :visible.sync="templateDialogVisible"
      width="650px"
      class="custom-dialog"
    >
      <el-form :model="templateForm" :rules="templateRules" ref="templateForm" label-width="100px">
        <el-form-item label="关联签名" prop="signatureId">
          <el-select v-model="templateForm.signatureId" style="width: 100%;" filterable placeholder="请选择关联签名" clearable @change="handleSignatureChange">
            <el-option v-for="item in signaturesList" :key="item.signatureId" :label="item.signatureName" :value="item.signatureId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模版名称" prop="templateName">
          <el-input v-model="templateForm.templateName" placeholder="请输入模版名称"></el-input>
        </el-form-item>
        <el-form-item label="模版分组" prop="groupId">
          <treeselect
            v-model="templateForm.groupId"
            :options="parentGroupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择模版分组"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="模版内容" prop="templateContent">
          <el-input
            type="textarea"
            v-model="templateForm.templateContent"
            :rows="6"
            placeholder="请输入模版内容，可使用${name}、${code}等变量"
            @input="updateCharCount"
          ></el-input>
          <div class="content-footer">
            <div class="variable-buttons">
              <el-dropdown @command="insertVariable" trigger="click">
                <el-button type="text" size="small">
                  插入变量<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-for="variable in variableList" :key="variable.variableId" :command="variable.variableCode">
                    {{ variable.variableName }}({{ variable.variableCode }})
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="char-counter" :class="{ 'warning': charCount > 400 }">
              <span>{{ charCount }}/500字符</span>
              <span class="message-count">({{ messageCount }}条消息)</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="申请说明" prop="applyDescription">
          <el-input
            type="textarea"
            v-model="templateForm.applyDescription"
            :rows="3"
            placeholder="请简要说明模板用途，有助于提高审核通过率"
          ></el-input>
        </el-form-item>
      </el-form>

      <div class="template-preview-box">
        <div class="preview-title">预览效果</div>
        <div class="preview-content">
          <div class="preview-message">
            <span class="preview-signature">【{{ templateForm.signatureName }}】</span>
            {{ previewDialogContent }}
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="templateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTemplateForm">提 交</el-button>
      </div>
    </el-dialog>


    <!-- 模板预览对话框 -->
    <el-dialog
      title="模板预览"
      :visible.sync="previewDialogVisible"
      width="400px"
      center
      class="custom-dialog"
    >
      <div class="preview-dialog-content">
        <div class="phone-preview-large">
          <div class="phone-frame">
            <div class="phone-header">
              <div class="phone-time">{{ currentTime }}</div>
            </div>
            <div class="phone-content">
              <div class="message-bubble">
                <div class="message-sender">【{{ templateForm.signatureName }}】</div>
                <div class="message-content">{{ previewDialogContent }}</div>
                <div class="message-time">{{ currentTime }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleUseTemplate">使用此模板</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改短信发送对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="sendForm" :model="sendForm" :rules="sendRules" label-width="80px">
        <el-form-item label="对应帐号" prop="smsKey">
          <el-input v-model="sendForm.smsKey" />
        </el-form-item>
        <el-form-item label="对应签名" prop="smsSignature">
          <el-input v-model="sendForm.smsSignature" placeholder="请输入对应签名" />
        </el-form-item>
        <el-form-item label="发送手机" prop="smsMobile">
          <el-input v-model="sendForm.smsMobile" placeholder="请输入手机号" />
        </el-form-item>
        <p style="margin-left: 80px;color: blue;">多个号码示例:18399829821,18499839328</p>
        <el-form-item label="发送内容" prop="smsContent">
          <el-input v-model="sendForm.smsContent" type="textarea" :rows="2" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSendSmsForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    <el-dialog
      title="导入模板"
      :visible.sync="importDialogVisible"
      width="500px"
      class="custom-dialog"
    >
      <div class="import-dialog-content">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :http-request="handleImportUpload"
          :on-change="handleImportFileChange"
          :on-remove="handleImportFileRemove"
          :file-list="importFileList"
          :auto-upload="false"
          :limit="1"
          accept=".json,.csv,.xlsx"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">支持 JSON、CSV、Excel 格式，请确保文件格式正确</div>
        </el-upload>

        <div class="import-tips">
          <p>导入说明：</p>
          <p>1. 文件中需包含模板名称、类型、内容等字段</p>
          <p>2. 导入的模板需要重新提交审核</p>
          <p>3. <a href="javascript:;" @click="downloadImportTemplate">下载导入模板示例</a></p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmImport" :disabled="importFileList.length === 0">导 入</el-button>
      </div>
    </el-dialog> -->

    <!-- 新增分组对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="groupDialogVisible"
      width="400px"
      class="custom-dialog"
    >
      <el-form :model="groupForm" :rules="groupRules" ref="groupForm" label-width="80px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="groupForm.groupName" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item label="上级分组" prop="parentId">
          <treeselect
            v-model="groupForm.parentId"
            :options="parentGroupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择上级分组"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="groupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGroupForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, auditTemplate } from "@/api/Sms/template";
import { sendSms } from "@/api/Sms/SmsRecord";
import { listSignatures } from "@/api/Sms/signatures";
import { listVariable } from "@/api/Sms/variable";
import { addSmstemlategroup, delSmstemlategroup, getSmstemlategroup, listSmstemlategroup, updateSmstemlategroup} from "@/api/Sms/smstemlategroup";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: 'SmsNoticeTemplate',
  components: { Treeselect },
  dicts: ["audit_status"],
  data() {
    return {
      // 筛选条件
      loading:  false,
      searchQuery: '',

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 选中的模板
      selectedTemplate: null,
      signaturesList: [],
      // 变量列表
      variableList: [
      ],
      templateForm: {
        id: null,
        signatureId: null,
        signatureName:  null,
        templateName: null,
        templateType: 1,
        templateContent: null,
        applyDescription: null,
        auditStatus: 'pending',
        auditDescription: null,
        auditTime: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null,
        remark: null,
        variables: [],
        groupId: null
      },
      // 对话框
      templateDialogVisible: false,
      variableDialogVisible: false,
      previewDialogVisible: false,
      importDialogVisible: false,

      // 对话框类型
      dialogType: 'create',

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        templateType: 1,
        templateContent: null,
        applyDescription: null,
        auditStatus: null,
        groupId:0,
        userId: this.$store.state.user.userId,
      },
      // 短信模板表格数据
      templateList: [],
      // 模板表单验证规则
      templateRules: {
        signatureId: [
          { required: true, message: "客户签名不能为空", trigger: "blur" }
        ],
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        templateType: [
          { required: true, message: "模板类型不能为空", trigger: "change" }
        ],
        templateContent: [
          { required: true, message: "模板内容不能为空", trigger: "blur" }
        ],
        applyDescription: [
          { required: true, message: "申请说明不能为空", trigger: "blur" }
        ],
        groupId: [
          { required: true, message: "请选择模板分组", trigger: "change" }
        ]
      },


      // 字符计数
      charCount: 0,
      messageCount: 1,

      // 导入文件
      importFileList: [],
      title: "",
      // 是否显示弹出层
      open: false,
      sendForm: {
        smsKey: "556bbe93de20f4bc9b925e0f8ffd5db3",
        smsLx: "1",
        smsContent: "测试001",
        smsMobile: "18395859595",
        smsSignature: "SIG_202504_5153",
      },
      // 表单校验
      sendRules: {
        smsKey: [
          { required: true, message: "帐号不能为空", trigger: "blur" }
        ],
        smsContent: [
          { required: true, message: "发送内容不能为空", trigger: "blur" }
        ],
        smsMobile: [
          { required: true, message: "发送手机不能为空", trigger: "blur" }
        ],
        smsSignature: [
          { required: true, message: "签名不能为空", trigger: "blur" }
        ],
      },

      // 模板分组相关
      templateGroups: [],
      flatGroups: [],
      defaultProps: {
        children: 'children',
        label: 'groupName'
      },
      groupDialogVisible: false,
      groupForm: {
        groupId: null,
        groupName: '',
        parentId: 0
      },
      groupRules: {
        groupName: [
          { required: true, message: '请输入分组名称', trigger: 'blur' },
          { min: 1, max: 50, message: '分组名称长度不能超过50个字符', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择上级分组', trigger: 'change' }
        ]
      },
      currentGroupId: null,
    }
  },
  created() {
    this.getList();
    this.getSignaturesList();
    this.getVariableList();
    this.getTemplateGroupTree();
  },
  computed: {

    // 当前时间
    currentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },

    // 表格样式
    tableHeaderStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 500,
        height: '50px'
      }
    },

    // 父级分组选项
    parentGroupOptions() {
      // 添加根节点
      const rootOption = {
        id: 0,
        groupId: 0,
        groupName: '全部模板',
        children: []
      };

      // 如果有分组数据，将其作为根节点的子节点
      if (this.templateGroups && this.templateGroups.length > 0) {
        // 过滤掉根节点本身，只取其子节点
        const children = this.templateGroups[0]?.children || [];
        rootOption.children = children;
      }

      return [rootOption];
    },

    // 预览内容
    previewContent() {
      if (!this.selectedTemplate) return '';

      let content = this.selectedTemplate.templateContent || '';

      // 替换变量
      this.variableList.forEach(variable => {
        const regex = new RegExp(`\\$\\{${variable.variableCode}\\}`, 'g');
        content = content.replace(regex, variable.variableExample || '示例值');
      });

      return content;
    },

    // 对话框预览内容
    previewDialogContent() {
      // 根据情况选择显示的内容 - 如果是在预览对话框中，使用selectedTemplate的内容
      let content = '';

      if (this.previewDialogVisible && this.selectedTemplate) {
        // 预览现有模板
        content = this.selectedTemplate.templateContent || '';
      } else {
        // 新建/编辑模板的预览
        content = this.templateForm.templateContent || '';
      }

      // 替换变量
      this.variableList.forEach(variable => {
        const regex = new RegExp(`\\$\\{${variable.variableCode}\\}`, 'g');
        content = content.replace(regex, variable.variableExample || '示例值');
      });

      return content;
    },

    // Add computed properties for filtered groups if needed
    systemGroups() {
      return this.flatGroups.filter(group => group.id <= 3);
    },

    customGroups() {
      return this.flatGroups.filter(group => group.id > 3);
    },
  },
  methods: {
    // treeselect 数据转换器
    normalizer(node) {
      return {
        id: node.groupId || node.id,
        label: node.groupName || node.name,
        children: node.children
      };
    },

    /** 查询短信模板列表 */
    getList() {
      this.loading = true;
      // 添加分组ID筛选条件
      if (this.currentGroupId) {
        this.queryParams.groupId = this.currentGroupId;
      }
      this.queryParams.userId = this.$store.state.user.userId;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取签名列表 */
    getSignaturesList() {
      listSignatures({pageSize: 100, auditStatus: 'successful',userId :this.$store.state.user.userId}).then(response => {
        this.signaturesList = response.rows;
      });
    },
    /** 获取模板变量列表 */
    getVariableList() {
      listVariable({pageSize: 100}).then(response => {
        this.variableList = response.rows;
      });
    },
    /** 新增按钮操作 */
    sendSmsTest() {
      this.sendForm.smsKey = "556bbe93de20f4bc9b925e0f8ffd5db3";
      this.sendForm.smsContent = this.selectedTemplate.templateContent;
      this.sendForm.smsMobile = "18395859595";
      this.sendForm.smsSignature=this.selectedTemplate.signatureId;

      this.open = true;
      this.title = "短信发送";
    },
    /** 处理签名变更 */
    handleSignatureChange(signatureId) {
      if (signatureId) {
        const selectedSignature = this.signaturesList.find(item => item.signatureId === signatureId);
        if (selectedSignature) {
          this.templateForm.signatureName = selectedSignature.signatureName;
        }
      } else {
        this.templateForm.signatureName = null;
      }
    },
    // 处理筛选变更
    handleFilterChange() {
      this.currentPage = 1;
      // 实现筛选逻辑
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 处理搜索
    handleSearch() {
      this.queryParams.userId= this.userId;
      // 将搜索关键词设置到查询参数中
      if (this.searchQuery && this.searchQuery.trim()) {
        this.queryParams.templateName = this.searchQuery.trim();
      } else {
        this.queryParams.templateName = null;
      }

      this.queryParams.pageNum = 1; // 重置到第一页
      this.getList(); // 重新加载列表
    },

    // 重置搜索
    resetSearch() {
      this.searchQuery = '';
      this.queryParams.templateName = null;
      this.queryParams.auditStatus = null;
      this.queryParams.pageNum = 1;
      this.getList(); // 重新加载列表
    },

    // 处理行点击
    handleRowClick(row) {
      this.selectedTemplate = row;
    },
    // 创建模板
    handleCreateTemplate() {
      this.dialogType = 'create';
      // 初始化表单数据
      this.templateForm = {
        templateId: null,
        signatureId: null,
        signatureName: null,
        templateName: '',
        templateType: 1,
        templateContent: '',
        applyDescription: '',
        auditStatus: 'pending',
        groupId: 0 // Default to 'All Templates' group
      };
      this.charCount = 0;
      this.messageCount = 1;
      this.templateDialogVisible = true;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.templateId || this.ids
      getTemplate(id).then(response => {
        this.templateForm = response.data;
        console.log("Template data:", this.templateForm);

        // Handle groupId properly
        if (this.templateForm.groupId === undefined ||
            this.templateForm.groupId === null ||
            this.templateForm.groupId === "undefined") {
          this.templateForm.groupId = 0; // Default to 'All Templates'
        } else {
          // Ensure it's a number
          this.templateForm.groupId = Number(this.templateForm.groupId);
        }

        // 如果有签名ID，获取对应的签名名称
        if (this.templateForm.signatureId) {
          const selectedSignature = this.signaturesList.find(item => item.signatureId === this.templateForm.signatureId);
          if (selectedSignature) {
            this.templateForm.signatureName = selectedSignature.signatureName;
          }
        }
        this.dialogType = 'edit';

        this.updateCharCount();
        this.templateDialogVisible = true;
      }).catch(error => {
        console.error("获取模版失败:", error);
        this.$message.error("获取模版失败: " + (error.message || "未知错误"));
      });
    },
    // 更新字符计数
    updateCharCount() {
      this.charCount = this.templateForm.templateContent ? this.templateForm.templateContent.length : 0;
      this.messageCount = Math.ceil(this.charCount / 70);
    },
    // 预览模板
    handlePreviewTemplate(template) {
      this.selectedTemplate = template;
      // 在打开预览对话框之前，临时将当前签名名称设置到templateForm中，用于显示
      if (template.signatureName) {
        this.templateForm.signatureName = template.signatureName;
      } else {
        this.templateForm.signatureName = '云服务';
      }
      this.previewDialogVisible = true;
    },
    // 复制模板
    handleCopyTemplate(template) {
      this.dialogType = 'create';
      // 复制模板信息但不保留ID，重置审核状态
      this.templateForm = {
        templateId: null,
        signatureId: template.signatureId,
        signatureName: template.signatureName,
        templateName: template.templateName + ' (复制)',
        templateType: template.templateType,
        templateContent: template.templateContent,
        applyDescription: template.applyDescription || '',
        auditStatus: 'pending'  // 新复制的模板默认为待审核
      };
      this.updateCharCount();
      this.templateDialogVisible = true;
    },

    // 删除模板
    handleDelete(row) {
      const ids = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除短信模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 发送按钮 */
    submitSendSmsForm() {

      this.$refs["sendForm"].validate(valid => {
        if (valid) {
          sendSms(this.sendForm).then(response => {
            this.$modal.msgSuccess("发送成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 插入变量
    insertVariable(code) {
      const variable = `\${${code}}`;

      const textarea = document.querySelector('textarea[name="templateContent"]');
      if (textarea) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;

        this.templateForm.templateContent = this.templateForm.templateContent.substring(0, start) +
          variable +
          this.templateForm.templateContent.substring(end);

        this.$nextTick(() => {
          textarea.selectionStart = start + variable.length;
          textarea.selectionEnd = start + variable.length;
          textarea.focus();
        });
      } else {
        this.templateForm.templateContent += variable;
      }

      this.updateCharCount();
    },
    /** 提交按钮 */
    submitTemplateForm() {
      this.$refs["templateForm"].validate(valid => {
        if (valid) {
          // 确保signatureName与signatureId匹配
          if (this.templateForm.signatureId && !this.templateForm.signatureName) {
            const selectedSignature = this.signaturesList.find(item => item.signatureId === this.templateForm.signatureId);
            if (selectedSignature) {
              this.templateForm.signatureName = selectedSignature.signatureName;
            }
          }

          // 验证审核状态，防止修改已审核通过的模板
          if (this.templateForm.templateId && this.templateForm.auditStatus === 'successful') {
            this.$message.warning('审核成功的模版不能修改');
            return;
          }

          // Create a clean copy of the form data to send to the server
          const formData = { ...this.templateForm };

          // Handle groupId properly
          if (formData.groupId === undefined || formData.groupId === null || formData.groupId === "undefined") {
            // If groupId is not valid, set it to the default group (0)
            formData.groupId = 0;
          } else {
            // Otherwise ensure it's a number
            formData.groupId = Number(formData.groupId);
          }

          console.log("Submitting template with data:", formData);

          if (formData.templateId != null) {
            updateTemplate(formData).then(response => {
              this.$message.success("修改成功");
              this.templateDialogVisible = false;
              this.getList();
            }).catch(error => {
              console.error("修改失败:", error);
              this.$message.error("修改失败: " + (error.message || "请检查表单数据"));
            });
          } else {
            addTemplate(formData).then(response => {
              this.$message.success("新增成功");
              this.templateDialogVisible = false;
              this.getList();
            }).catch(error => {
              console.error("新增失败:", error);
              this.$message.error("新增失败: " + (error.message || "请检查表单数据"));
            });
          }
        }
      });
    },
    // 使用模板
    handleUseTemplate() {
      this.$router.push({
        name: 'SmsMassMessaging',
        query: { templateId: this.selectedTemplate.id }
      });
    },

    /** 获取模板分组树 */
    getTemplateGroupTree() {
      this.loading = true;
      const queryParams = {
        userId: this.$store.state.user.userId
      };

      listSmstemlategroup(queryParams).then(response => {
        if (response.code === 200) {
          // 处理返回的树数据
          this.templateGroups = this.processTreeData(response.data || []);
          // 生成扁平化的分组列表，用于下拉选择
          this.flatGroups = this.flattenGroups(this.templateGroups);
        } else {
          this.$message.error('获取模板分组失败');
          // 如果获取失败，至少显示根节点
          this.templateGroups = this.processTreeData([]);
          this.flatGroups = [];
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取模板分组出错', error);
        this.$message.error('获取模板分组失败');
        // 如果获取失败，至少显示根节点
        this.templateGroups = this.processTreeData([]);
        this.flatGroups = [];
        this.loading = false;
      });
    },

    // 处理树数据，添加图标等信息
    processTreeData(treeData) {
      // 确保 treeData 是数组
      if (!Array.isArray(treeData)) {
        console.warn('Tree data is not an array:', treeData);
        treeData = [];
      }

      const processNode = (node) => {
        // 确保节点有必要的属性
        const processedNode = {
          ...node,
          groupId: node.groupId || node.id,
          groupName: node.groupName || node.name,
          children: []
        };

        // 设置节点图标和类型
        if (!processedNode.parentId || processedNode.parentId === '0' || processedNode.parentId === 0) {
          processedNode.icon = 'el-icon-folder-opened';
          processedNode.type = processedNode.groupId <= 3 ? 'system' : 'user';
        } else {
          processedNode.icon = 'el-icon-folder';
          processedNode.type = 'user';
        }

        // 递归处理子节点
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
          processedNode.children = node.children.map(child => processNode(child));
        }

        return processedNode;
      };

      // 构建树形结构 - 如果后端返回的不是树形结构，则需要构建
      let processedData = [];

      if (treeData.length > 0 && treeData[0].children !== undefined) {
        // 后端返回的已经是树形结构
        processedData = treeData.map(node => processNode(node));
      } else {
        // 后端返回的是扁平结构，需要构建树形结构
        processedData = this.buildTreeFromFlat(treeData).map(node => processNode(node));
      }

      // 添加"全部模板"根节点
      const rootNodes = [{
        groupId: 0,
        id: 0,
        groupName: '全部模板',
        icon: 'el-icon-s-home',
        type: 'system',
        children: processedData
      }];

      return rootNodes;
    },

    // 从扁平数据构建树形结构
    buildTreeFromFlat(flatData) {
      if (!Array.isArray(flatData) || flatData.length === 0) {
        return [];
      }

      // 创建映射对象
      const idMap = {};
      const tree = [];

      // 第一遍遍历，创建所有节点
      flatData.forEach(item => {
        const node = {
          ...item,
          children: []
        };
        idMap[item.groupId || item.id] = node;
      });

      // 第二遍遍历，建立父子关系
      flatData.forEach(item => {
        const node = idMap[item.groupId || item.id];
        const parentId = item.parentId;

        if (parentId && parentId !== 0 && parentId !== '0' && idMap[parentId]) {
          // 有父节点，添加到父节点的children中
          idMap[parentId].children.push(node);
        } else {
          // 没有父节点或父节点是0，添加到根级
          tree.push(node);
        }
      });

      return tree;
    },

    // 处理树节点点击
    handleNodeClick(data) {
      console.log('点击节点:', data);
      if (data.groupId === 0) {
        // 点击"全部模板"，清除分组筛选
        this.currentGroupId = null;
        this.queryParams.groupId = null;
      } else {
        // 点击具体分组，设置分组ID筛选
        this.currentGroupId = data.groupId;
        this.queryParams.groupId = data.groupId;
      }

      // 重新加载模板列表
      this.getList();
    },
    /** 新增按钮操作 */

    // 新建分组
    handleAddGroup(parentData) {
      this.groupForm = {
        groupId: null,
        groupName: '',
        parentId: parentData && parentData.groupId ? parseInt(parentData.groupId, 10) : 0
      };
      this.groupDialogVisible = true;
      this.title = "新建分组";
    },
    /** 修改按钮操作 */
    handleGroupUpdate(row) {
      // 检查groupId是否有效
      if (!row || row.groupId === undefined || row.groupId === null) {
        this.$message.error('分组ID无效，无法编辑');
        return;
      }

      // 确保groupId是数字类型
      const groupId = parseInt(row.groupId, 10);
      if (isNaN(groupId) || groupId <= 0) {
        this.$message.error('分组ID无效，无法编辑');
        return;
      }

      getSmstemlategroup(groupId).then(response => {
        if (response.code === 200 && response.data) {
          this.groupForm = {
            ...response.data,
            // 确保数值类型正确
            groupId: parseInt(response.data.groupId, 10),
            parentId: parseInt(response.data.parentId, 10) || 0
          };
          this.groupDialogVisible = true;
          this.title = "修改分组";
        } else {
          this.$message.error('获取分组信息失败');
        }
      }).catch(error => {
        console.error('获取分组信息出错', error);
        this.$message.error('获取分组信息失败: ' + (error.message || '未知错误'));
      });
    },
    /** 删除按钮操作 */
    handleGroupDelete(node, data) {
      // 检查groupId是否有效
      if (!data || data.groupId === undefined || data.groupId === null) {
        this.$message.error('分组ID无效，无法删除');
        return;
      }

      // 确保groupId是数字类型
      const groupId = parseInt(data.groupId, 10);
      if (isNaN(groupId) || groupId <= 0) {
        this.$message.error('分组ID无效，无法删除');
        return;
      }

      this.$confirm(`确定要删除分组"${data.groupName}"吗？删除后分组内的模板将移至默认分组。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API，传递数字类型的groupId
        delSmstemlategroup(groupId).then(response => {
          if (response.code === 200) {
            this.$message.success('删除分组成功');
            // 如果当前选中的是被删除的分组，切换到全部模板
            if (this.currentGroupId === groupId) {
              this.currentGroupId = null;
              this.queryParams.groupId = null;
              this.getList(); // 重新加载模板列表
            }
            // 刷新分组树
            this.getTemplateGroupTree();
          } else {
            this.$message.error('删除分组失败: ' + (response.msg || '未知错误'));
          }
        }).catch(error => {
          console.error('删除分组出错', error);
          this.$message.error('删除分组失败: ' + (error.message || '未知错误'));
        });
      }).catch(() => {
        // 取消删除操作
      });
    },
    // 提交分组表单
    submitGroupForm() {
      this.$refs.groupForm.validate(valid => {
        if (valid) {
          const data = {
            groupName: this.groupForm.groupName,
            parentId: parseInt(this.groupForm.parentId, 10) || 0,
            userId: this.$store.state.user.userId
          };

          // 判断是新增还是编辑
          if (this.groupForm.groupId) {
            // 编辑模式
            data.groupId = parseInt(this.groupForm.groupId, 10);

            updateSmstemlategroup(data).then(response => {
              if (response.code === 200) {
                this.$message.success('修改分组成功');
                this.groupDialogVisible = false;
                this.getTemplateGroupTree(); // 刷新分组树
              } else {
                this.$message.error('修改分组失败: ' + (response.msg || '未知错误'));
              }
            }).catch(error => {
              console.error('修改分组出错', error);
              this.$message.error('修改分组失败: ' + (error.message || '未知错误'));
            });
          } else {
            // 新增模式
            addSmstemlategroup(data).then(response => {
              if (response.code === 200) {
                this.$message.success('添加分组成功');
                this.groupDialogVisible = false;
                this.getTemplateGroupTree(); // 刷新分组树
              } else {
                this.$message.error('添加分组失败: ' + (response.msg || '未知错误'));
              }
            }).catch(error => {
              console.error('添加分组出错', error);
              this.$message.error('添加分组失败: ' + (error.message || '未知错误'));
            });
          }
        }
      });
    },

    // 扁平化分组树，用于下拉选择
    flattenGroups(groups, result = []) {
      if (!Array.isArray(groups)) {
        return result;
      }

      groups.forEach(group => {
        if (group.groupId !== 0) { // 排除"全部模板"节点
          result.push({
            id: Number(group.groupId), // Ensure it's a number
            name: group.groupName
          });
        }

        if (group.children && Array.isArray(group.children) && group.children.length > 0) {
          this.flattenGroups(group.children, result);
        }
      });

      return result;
    },
  },
}
</script>

<style scoped>
.sms-template-container {
  padding: 10px;
  background-color: #f8f9fa;
  height: calc(100vh - 84px); /* Adjust 84px based on your actual navbar height */
  display: flex;
  flex-direction: column;
}

/* Make the main row flexible */
.sms-template-container > .el-row {
  flex-grow: 1;
  display: flex;
}

/* Make columns flexible */
.sms-template-container > .el-row > .el-col {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* Make cards grow to fill the column */
.sms-template-container .el-card {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

/* Make card body scrollable and flexible */
.sms-template-container .el-card >>> .el-card__body {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
}

/* Ensure detail card content is laid out correctly */
.template-detail-card >>> .el-card__body {
  display: flex;
  flex-direction: column;
}

.template-detail-content {
  height: 100%;
}

.empty-details-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  font-size: 22px;
  color: #303133;
  margin: 0;
  font-weight: 500;
}

.version-tag {
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  padding: 0 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 信息提示条样式 */
.info-alert {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #374151;
}

.header-title i {
  margin-right: 8px;
  font-size: 18px;
  color: #3b82f6;
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  padding: 6px;
  border-radius: 6px;
}

.add-group-btn {
  color: #3b82f6;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #dbeafe;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.3s ease;
  font-weight: 500;
}

.add-group-btn:hover {
  color: #ffffff;
  background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
  border-color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.add-group-btn i {
  font-size: 12px;
  margin-right: 4px;
}

/* 模板列表卡片样式 */
.template-list-card {
  margin-bottom: 10px;
  border-radius: 4px;
}

/* 筛选工具栏样式 */
.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.right-section {
  display: flex;
  gap: 10px;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

/* 模板详情卡片样式 */
.template-detail-card {
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.template-content-preview {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.5;
  word-break: break-all;
}

.reject-reason {
  color: #f56c6c;
}

/* 模板预览区域样式 */
.template-preview-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.phone-preview {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.phone-frame {
  width: 240px;
  height: 400px;
  border: 8px solid #303133;
  border-radius: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;
}

.phone-header {
  height: 40px;
  background-color: #303133;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}

.message-bubble {
  background-color: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-sender {
  font-weight: 500;
  margin-bottom: 8px;
  color: #409eff;
}

.message-content {
  line-height: 1.5;
  word-break: break-all;
}

.message-time {
  text-align: right;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 变量管理卡片样式 */
.variables-card {
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.variables-list {
  margin-bottom: 16px;
}

.variables-tips {
  font-size: 12px;
  color: #909399;
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  line-height: 1.5;
}

.variables-tips p {
  margin: 4px 0;
}

/* 内容底部样式 */
.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.variable-buttons {
  display: flex;
  gap: 8px;
}

.char-counter {
  font-size: 12px;
  color: #606266;
}

.char-counter.warning {
  color: #e6a23c;
}

.message-count {
  margin-left: 4px;
  color: #409eff;
}

/* 模板预览框样式 */
.template-preview-box {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.preview-title {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  color: #303133;
}

.preview-content {
  padding: 15px;
  background-color: #fff;
}

.preview-message {
  line-height: 1.5;
  word-break: break-all;
}

.preview-signature {
  color: #409eff;
  font-weight: 500;
}

/* 预览对话框样式 */
.preview-dialog-content {
  display: flex;
  justify-content: center;
}

.phone-preview-large .phone-frame {
  width: 280px;
  height: 500px;
}

/* 导入对话框样式 */
.import-dialog-content {
  margin-bottom: 20px;
}

.import-tips {
  margin-top: 20px;
  font-size: 12px;
  color: #606266;
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  line-height: 1.5;
}

.import-tips p {
  margin: 4px 0;
}

.import-tips a {
  color: #409eff;
  text-decoration: none;
}

/* 自定义表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.custom-table >>> .el-table__header-wrapper th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
}

.custom-table >>> .el-table__row:hover {
  background-color: #f5f7fa;
}

/* 自定义按钮样式 */
.custom-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.primary-button {
  background-color: #409eff;
  border-color: #409eff;
}

.primary-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 操作按钮样式 */
.action-button {
  color: #409eff;
  margin-right: 10px;
}

.action-button:hover {
  color: #66b1ff;
}

/* 空数据状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.empty-image {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
}

.empty-text {
  color: #909399;
  font-size: 14px;
}

/* 对话框样式 */
.custom-dialog >>> .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog >>> .el-dialog__title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.custom-dialog >>> .el-dialog__body {
  padding: 20px;
}

.custom-dialog >>> .el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

/* 模板分组树样式 */
.template-group-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e8ecf0;
  transition: box-shadow 0.3s ease;
}

.template-group-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.template-group-card .el-card__header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px 8px 0 0;
}

.template-group-card .el-card__body {
  padding: 8px 0;
}

/* 统一的el-tree样式 */
.template-group-card .el-tree {
  background-color: transparent;
}

.template-group-card .el-tree-node {
  margin-bottom: 4px;
}

.template-group-card >>> .el-tree-node__content {
  height: 36px !important;
  line-height: 36px !important;
  min-height: 36px !important;
  padding: 0 10px 0 0 !important;
}

.template-group-card .el-tree-node__expand-icon {
  padding: 6px;
}

.template-group-card .el-tree-node__label {
  font-size: 14px;
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 0px;
  font-size: 14px;
  height: 36px;
  line-height: 36px;
}

.node-label {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: 400;
  transition: all 0.3s ease;
}

.tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

.node-actions {
  display: none;
  gap: 4px;
}

.custom-tree-node:hover .node-actions {
  display: flex;
}

.action-icon {
  margin-left: 8px;
  font-size: 14px;
  color: #9ca3af;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-icon:hover {
  color: #ffffff;
  background: #3b82f6;
}

.tree-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 120px;
  color: #6b7280;
  font-size: 14px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  margin: 12px;
}

.tree-loading i {
  margin-right: 8px;
  font-size: 20px;
  color: #3b82f6;
  animation: loading-spin 1.5s linear infinite;
}

@keyframes loading-spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Treeselect 组件样式 - 与Element UI标准控件一致 */
::v-deep .vue-treeselect {
  font-size: 14px;
}

::v-deep .vue-treeselect__control {
  height: 40px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  background: #ffffff;
  font-family: inherit;
}

::v-deep .vue-treeselect__control:hover {
  border-color: #c0c4cc;
}

::v-deep .vue-treeselect__control--is-focused {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  line-height: 38px;
  color: #606266;
  font-size: 14px;
}

::v-deep .vue-treeselect__menu {
  border: 1px solid #E4E7ED;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #ffffff;
  z-index: 9999;
  max-width: 300px;
  min-width: 220px;
}

::v-deep .vue-treeselect__list {
  max-height: 280px;
  overflow-y: auto;
  padding: 6px 0;
}

/* 统一选项样式 - 与Element UI Select保持一致 */
::v-deep .vue-treeselect__option {
  padding: 0;
  margin: 0;
  border-radius: 0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: flex;
  align-items: center;
  min-height: 34px;
  font-size: 14px;
  color: #606266;
}

::v-deep .vue-treeselect__option:hover {
  background-color: #f5f7fa;
}

::v-deep .vue-treeselect__option--selected {
  background-color: #f5f7fa;
  color: #409EFF;
  font-weight: 500;
}

::v-deep .vue-treeselect__option--selected:hover {
  background-color: #f5f7fa;
}

/* 展开箭头容器 */
::v-deep .vue-treeselect__option-arrow-container {
  width: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

/* 展开箭头样式 - 使用标准颜色 */
::v-deep .vue-treeselect__option-arrow {
  border-left: 5px solid #C0C4CC;
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
  transition: all 0.3s ease;
}

::v-deep .vue-treeselect__option--expanded .vue-treeselect__option-arrow {
  transform: rotate(90deg);
  border-left-color: #909399;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__option-arrow {
  border-left-color: #909399;
}

/* 标签容器统一对齐 */
::v-deep .vue-treeselect__label-container {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 0 12px;
  min-height: 34px;
}

::v-deep .vue-treeselect__label {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
  flex: 1;
  font-weight: 400;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__label {
  color: #606266;
}

::v-deep .vue-treeselect__option--selected .vue-treeselect__label {
  color: #409EFF;
  font-weight: 500;
}

/* 层级缩进 - 与Element UI Tree保持一致 */
::v-deep .vue-treeselect__indent-level-1 .vue-treeselect__label-container {
  padding-left: 32px;
}

::v-deep .vue-treeselect__indent-level-2 .vue-treeselect__label-container {
  padding-left: 52px;
}

::v-deep .vue-treeselect__indent-level-3 .vue-treeselect__label-container {
  padding-left: 72px;
}

::v-deep .vue-treeselect__indent-level-4 .vue-treeselect__label-container {
  padding-left: 92px;
}

/* 根节点样式 - 简化为标准样式 */
::v-deep .vue-treeselect__option[data-id="0"] {
  background: transparent;
  border: none;
  border-radius: 0;
  margin: 0;
}

::v-deep .vue-treeselect__option[data-id="0"] .vue-treeselect__label-container {
  padding: 0 12px;
}

::v-deep .vue-treeselect__option[data-id="0"] .vue-treeselect__label {
  color: #606266;
  font-weight: 500;
  font-size: 14px;
}

::v-deep .vue-treeselect__option[data-id="0"]:hover {
  background: #f5f7fa;
  border: none;
}

::v-deep .vue-treeselect__option[data-id="0"]:hover .vue-treeselect__label {
  color: #606266;
}

::v-deep .vue-treeselect__option[data-id="0"]--selected {
  background: #f5f7fa;
  border: none;
}

::v-deep .vue-treeselect__option[data-id="0"]--selected .vue-treeselect__label {
  color: #409EFF;
  font-weight: 500;
}

/* 计数标签 - 使用Element UI标准样式 */
::v-deep .vue-treeselect__count {
  background: #f4f4f5;
  color: #909399;
  border-radius: 2px;
  padding: 1px 5px;
  font-size: 12px;
  margin-left: 6px;
  font-weight: 400;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 14px;
  height: 16px;
  line-height: 14px;
  flex-shrink: 0;
}

::v-deep .vue-treeselect__option:hover .vue-treeselect__count {
  background: #e4e7ed;
  color: #909399;
}

::v-deep .vue-treeselect__option--selected .vue-treeselect__count {
  background: #ecf5ff;
  color: #409EFF;
}

/* 下拉箭头 - 与Element UI一致 */
::v-deep .vue-treeselect__arrow-container {
  height: 38px;
  width: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .vue-treeselect__arrow {
  color: #C0C4CC;
  transition: color 0.3s ease;
  font-size: 14px;
}

::v-deep .vue-treeselect__control:hover .vue-treeselect__arrow {
  color: #909399;
}

::v-deep .vue-treeselect__control--is-focused .vue-treeselect__arrow {
  color: #409EFF;
}

/* 清除按钮 */
::v-deep .vue-treeselect__x-container {
  width: 30px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep .vue-treeselect__x {
  color: #C0C4CC;
  transition: color 0.3s ease;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

::v-deep .vue-treeselect__x:hover {
  color: #909399;
  background: rgba(144, 147, 153, 0.1);
}

/* 空状态 */
::v-deep .vue-treeselect__no-options {
  padding: 12px 16px;
  text-align: center;
  color: #C0C4CC;
  font-size: 14px;
}

/* 加载状态 */
::v-deep .vue-treeselect__loading {
  padding: 12px 16px;
  text-align: center;
  color: #C0C4CC;
  font-size: 14px;
}
</style>
